package com.coder.algorithm.offer_2;

/**
 * 左旋转字符串
 *
 * @author yuhushuan
 * @date 2020/7/2 09:28
 */
public class _58_2_LeftRotateString {
    private static String leftRotateString(String str, int n) {
        if (str == null || str.length() < n || n <= 0) {
            return str;
        }
        char[] result = str.toCharArray();
        // 将字符串分两部分翻转
        reverse(result, 0, n - 1);
        reverse(result, n, result.length - 1);
        reverse(result, 0, result.length - 1);
        return new String(result);
    }

    private static void reverse(char[] data, int start, int end) {
        if (data == null) {
            return;
        }
        while (start < end) {
            char temp = data[start];
            data[start] = data[end];
            data[end] = temp;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        // 功能测试
        // 长度为 n 左旋转 0 个字符
        print("abcdefg", 0);
        print("abcdefg", 1);
        print("abcdefg", 2);

        // n-1, n ,n+1
        print("abcdefg", 6);
        print("abcdefg", 7);
        print("abcdefg", 8);

        print(null,1);
    }

    private static void print(String str, int n) {
        System.out.println("字符串：" + str + " 的左旋转 " + n + " 个字符为：");
        System.out.println(leftRotateString(str, n));
        System.out.println();
    }
}
